package cn.schoolwow.util.module.query.jsonarray.flow.group;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class GroupJSONArrayByFieldBusiness implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        JSONArray filterArray = (JSONArray) flowContext.checkData("filterArray");
        String fieldName = (String) flowContext.checkData("fieldName");

        if(null==filterArray){
            return;
        }

        JSONObject fieldJSONArrayMap = new JSONObject();
        for(int i=0;i<filterArray.size();i++){
            JSONObject object = filterArray.getJSONObject(i);
            String fieldValue = object.getString(fieldName);
            if(!fieldJSONArrayMap.containsKey(fieldValue)){
                fieldJSONArrayMap.put(fieldValue, new JSONArray());
            }
            fieldJSONArrayMap.getJSONArray(fieldValue).add(object);
        }
        flowContext.putReturnData("fieldJSONArrayMap", fieldJSONArrayMap);
    }

    @Override
    public String name() {
        return "根据指定字段分组JSON数组";
    }
}